package com.example.myapplication.api

import android.content.Context
import android.util.Log
import com.example.myapplication.config.AppConfig
import com.example.myapplication.model.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

/**
 * 后端 API 客户端
 * 调用 Python FastAPI 后端服务
 */
class BackendApiClient(private val context: Context) {
    
    companion object {
        private const val TAG = "BackendAPI"
    }
    
    private val gson = Gson()
    
    /**
     * 获取配置的服务器URL
     */
    private fun getBaseUrl(): String {
        return AppConfig.getServerUrl(context)
    }
    
    /**
     * 获取热门股票列表
     */
    suspend fun getPopularStocks(): List<Stock> = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/stocks/popular")
            Log.d(TAG, "请求: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            Log.d(TAG, "响应码: $responseCode")
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val type = object : TypeToken<List<Stock>>() {}.type
                val stocks: List<Stock> = gson.fromJson(response, type)
                
                Log.d(TAG, "✅ 获取 ${stocks.size} 只股票")
                stocks
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 网络异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 获取推荐买入的股票列表（后台推荐，按时间排序）
     */
    suspend fun getRecommendedBuyStocks(): List<Stock> = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/stocks/recommended/buy")
            Log.d(TAG, "💰 请求推荐买入股票: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            Log.d(TAG, "响应码: $responseCode")
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val type = object : TypeToken<List<Stock>>() {}.type
                val stocks: List<Stock> = gson.fromJson(response, type)
                
                Log.d(TAG, "✅ 获取 ${stocks.size} 个推荐买入股票")
                stocks
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 网络异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 获取股票历史数据
     */
    suspend fun getStockHistory(symbol: String, days: Int = 90): List<StockPrice> = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/stocks/$symbol/history?days=$days")
            Log.d(TAG, "请求历史数据: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 15000
            connection.readTimeout = 15000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val type = object : TypeToken<List<StockPrice>>() {}.type
                val prices: List<StockPrice> = gson.fromJson(response, type)
                
                Log.d(TAG, "✅ 获取 ${prices.size} 条历史数据")
                prices
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取历史数据异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 获取交易信号
     */
    suspend fun getTradingSignal(symbol: String): TradingSignal? = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/stocks/$symbol/signal")
            Log.d(TAG, "请求交易信号: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 15000
            connection.readTimeout = 15000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val signal: TradingSignal = gson.fromJson(response, TradingSignal::class.java)
                
                Log.d(TAG, "✅ 获取交易信号: ${signal.signalType}")
                signal
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                null
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取交易信号异常: ${e.message}", e)
            null
        }
    }
    
    /**
     * 获取历史买卖点
     */
    suspend fun getTradingPoints(symbol: String): List<TradingPoint> = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/stocks/$symbol/trading-points")
            Log.d(TAG, "请求买卖点: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 15000
            connection.readTimeout = 15000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val type = object : TypeToken<List<TradingPoint>>() {}.type
                val points: List<TradingPoint> = gson.fromJson(response, type)
                
                Log.d(TAG, "✅ 获取 ${points.size} 个买卖点")
                points
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取买卖点异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 搜索股票
     */
    suspend fun searchStocks(query: String): List<Stock> = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val encodedQuery = java.net.URLEncoder.encode(query, "UTF-8")
            val url = URL("$baseUrl/stocks/search?q=$encodedQuery")
            Log.d(TAG, "搜索股票: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val type = object : TypeToken<List<Stock>>() {}.type
                val stocks: List<Stock> = gson.fromJson(response, type)
                
                Log.d(TAG, "✅ 搜索到 ${stocks.size} 只股票")
                stocks
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 搜索异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 批量分析股票
     */
    suspend fun analyzeBatchStocks(): List<StockAnalysis> = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/analysis/batch")
            Log.d(TAG, "批量分析股票: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 30000  // 30秒超时
            connection.readTimeout = 30000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val type = object : TypeToken<List<StockAnalysis>>() {}.type
                val analysis: List<StockAnalysis> = gson.fromJson(response, type)
                
                Log.d(TAG, "✅ 分析 ${analysis.size} 只股票")
                analysis
            } else {
                Log.e(TAG, "❌ 请求失败: $responseCode")
                emptyList()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 批量分析异常: ${e.message}", e)
            emptyList()
        }
    }
    
    /**
     * 注册设备FCM Token到后端服务器
     * 后端会使用这个token主动推送买卖点信号
     */
    suspend fun registerDeviceToken(token: String): Boolean = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/device/register")
            Log.d(TAG, "注册设备Token: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "POST"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            connection.setRequestProperty("Content-Type", "application/json")
            connection.doOutput = true
            
            // 发送JSON数据
            val jsonData = """{"token": "$token"}"""
            connection.outputStream.use { os ->
                os.write(jsonData.toByteArray())
            }
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                Log.d(TAG, "✅ Token注册成功")
                true
            } else {
                Log.e(TAG, "❌ Token注册失败: $responseCode")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ Token注册异常: ${e.message}", e)
            false
        }
    }
    
    /**
     * 启动后端监控服务
     * 后端会持续监控股票，发现买卖点时推送给所有注册的设备
     */
    suspend fun startBackendMonitoring(intervalSeconds: Int = 30): Boolean = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/monitoring/start?interval=$intervalSeconds")
            Log.d(TAG, "启动后端监控: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "POST"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                Log.d(TAG, "✅ 后端监控已启动")
                true
            } else {
                Log.e(TAG, "❌ 启动后端监控失败: $responseCode")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动后端监控异常: ${e.message}", e)
            false
        }
    }
    
    /**
     * 停止后端监控服务
     */
    suspend fun stopBackendMonitoring(): Boolean = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/monitoring/stop")
            Log.d(TAG, "停止后端监控: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "POST"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                Log.d(TAG, "✅ 后端监控已停止")
                true
            } else {
                Log.e(TAG, "❌ 停止后端监控失败: $responseCode")
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止后端监控异常: ${e.message}", e)
            false
        }
    }
    
    /**
     * 获取后端监控状态
     */
    suspend fun getMonitoringStatus(): MonitoringStatus? = withContext(Dispatchers.IO) {
        try {
            val baseUrl = getBaseUrl()
            val url = URL("$baseUrl/monitoring/status")
            Log.d(TAG, "查询监控状态: $url")
            
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 10000
            connection.readTimeout = 10000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = reader.readText()
                reader.close()
                
                val status: MonitoringStatus = gson.fromJson(response, MonitoringStatus::class.java)
                Log.d(TAG, "✅ 监控状态: ${status.isActive}")
                status
            } else {
                Log.e(TAG, "❌ 查询监控状态失败: $responseCode")
                null
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查询监控状态异常: ${e.message}", e)
            null
        }
    }
}

/**
 * 监控状态数据类
 */
data class MonitoringStatus(
    val isActive: Boolean,
    val intervalSeconds: Int,
    val monitoringStockCount: Int,
    val lastUpdateTime: Long,
    val registeredDevices: Int
)


